<template>
  <div style="height:6vh;padding:10px 20px;background-color:#fff;">
    <span style="line-height:60px;font-size:20px;">活动管理</span>
    <router-link to="/addActivity" class="ml-auto mt-2">

    <el-button type="primary" @click="dialogVisible = true"
               style="float: right;margin-top:10px;">新建活动</el-button>
    </router-link>
  </div>

  <!-- 用户搜索卡片 -->
  <el-card style="margin: 10px;height: 70px;">
    <el-form :inline="true">

      <el-form-item label="活动标题" style="width: 270px;">
        <el-input placeholder="请输入活动标题"
                  v-model="searchUserForm.activityName"
        @keydown.enter="loadUser"></el-input>
      </el-form-item>
<!--      <el-form-item label="活动" style="width: 270px;">
        <el-input placeholder="请输入活动标题"
                  v-model="searchUserForm.activityName"
        @keydown.enter="loadUser"></el-input>
      </el-form-item>-->
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadUser">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 用户列表卡片 用户表格数据-->
  <el-card style="margin: 10px;">
    <el-table :data="userArr">
      <el-table-column label="编号" type="index" width="80" align="center"></el-table-column>
      <el-table-column label="活动名称" prop="activityName" align="center"></el-table-column>
      <el-table-column label="活动开始时间" prop="startDate" align="center"></el-table-column>
      <el-table-column label="活动规则" prop="describes" align="center"></el-table-column>
      <el-table-column label="目标人群" prop="targetCustomer" align="center"></el-table-column>
      <el-table-column label="活动目标" prop="activityTarget" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary"
                     @click="handleEdit(scope.row)">编辑</el-button>
          <el-button link type="primary" :disabled="scope.row.level==40"
                     @click="deleteActivity(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 新增/编辑活动对话框 -->
  <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      :before-close="handleClose"
  >
    <el-form
        :model="taskForm"
        label-width="120px"
        label-position="top"
        ref="taskFormRef"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="活动名称" prop="name" required>
            <el-input v-model="taskForm.name" placeholder="请输入活动名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="请选择奖励类型" prop="template">
            <el-select
                v-model="taskForm.template"
                placeholder="请选择奖励类型"
                style="width:100%"
            >
              <el-option label="优惠券" value="template1" />
              <el-option label="积分" value="template2" />
              <el-option label="商品" value="template2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="活动目标" prop="target">
            <el-input v-model="taskForm.target" placeholder="请输入活动目标" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="活动时间" prop="time">
            <el-date-picker
                v-model="taskForm.time"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="resetTaskForm">重置</el-button>
      <el-button
          type="primary"
          @click="handleConfirm"
      >确定</el-button>
    </template>
  </el-dialog>

</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";
//定义变量控制弹窗是否出现
//定义对象来保存用户查询的条件
const searchUserForm = ref({activityName:''});
//定义对象保存查询到的用户表格数据
const userArr = ref([]);
//定义加载活动列表的方法
const loadUser = ()=>{
  let data = qs.stringify(searchUserForm.value);
  //如果有查询条件,就根据条件查,没有条件默认查全部数据
  axios.get('http://localhost:8087/vv1/activity/select?'+data)
      .then((response)=>{//回调函数,处理响应数据
        if(response.data.code==2000){//后端返回的状态码是2000说明成功了
          userArr.value = response.data.data;//把请求回来的数据装到绑定表格的数组中
          console.log('表格数据源 userArr：', userArr.value); // 检查每个对象是否有 id
          console.log(userArr.value);
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
//创建删除活动的方法
const deleteActivity = (activityId)=>{
  if(confirm('您确认要删除该活动吗?')){
    axios.post('http://localhost:8087/vv1/activity/delete/'+activityId).then((response)=>{
      if(response.data.code==2000){
        ElMessage.success('删除成功!');
        //删除成功后,需要重新加载用户列表
        loadUser();
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
}


//页面一加载完毕,立即执行
onMounted(()=>{
  loadUser();
})



//重置搜索
const resetSearch = ()=>{
  //清空之前的搜索内容
  searchUserForm.value = {};
  //重新加载所有的用户数据
  loadUser();
}

const handleConfirm = () => {
  console.log('确认时 editRow：', editRow);
  // 手动解包，确保拿到最新值
  const row = editRow.value;
  if (!row || !row.id) {
    ElMessage.error('请先选择有效活动进行编辑');
    return;
  }
  updateActivity(row.id);
};


const dialogVisible = ref(false)
const dialogTitle = ref('编辑活动')
const taskForm = reactive({
  id: '',
  name: '',
  time: [],         // 日期范围
  desc: '',
  target: '',
  store: '',        // 店铺ID（逗号分隔）
  crowd: '',        // 人群ID（逗号分隔）
  autoMarketing: false,
  channels: [],
  rewardType: '优惠券',
  reward: '',       // 奖励ID
  summary: '',
  link: ''
})
// 显示新增对话框
// 编辑任务
// 新增变量，保存当前编辑的行数据
const editRow = ref(null);
const handleEdit = (row) => {

  console.log('点击编辑的行数据：', row); // 看是否有id等完整数据
  // 暂存当前编辑的行数据
  editRow.value = row;
  console.log('editRow 原始对象：', editRow);
  dialogVisible.value = true;
  Object.assign(taskForm, {
    // 注意：这里要从 row 里取真实数据，之前错误地从 taskForm 取（taskForm 初始是空的，取不到值）
    id: row.id,
    name: row.activityName,
    time: [row.startDate, row.endDate],
    desc: row.describes,
    target: row.activityTarget,
    store: row.shopIds,
    crowd: row.targetCustomer,
    // 其他字段同理，从 row 对应属性取...
    rewardType: row.rewardType === 1 ? '优惠券' : row.rewardType === 2 ? '积分' : '商品',
    reward: row.rewardCouponId,
    summary: row.shareProfile,
    link: row.shareUrl,
    enableStatus: row.enableStatus,
    activityType: row.activityType,
    channelType: row.channelType
  });
  dialogVisible.value = true;
};

// 重置对话框表单
const resetTaskForm = () => {

  // 重置表单数据到初始状态
  taskForm.name = ''
  taskForm.time = []
  taskForm.desc = ''
  taskForm.target = ''
  taskForm.store = ''
  taskForm.crowd = ''
  taskForm.autoMarketing = false
  taskForm.channels = []
  taskForm.rewardType = '优惠券'
  taskForm.reward = ''
  taskForm.summary = ''
  taskForm.link = ''
}

// 提交任务
const submitTask = () => {
  // 表单验证和提交逻辑...
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetTaskForm() // 关闭对话框时也重置表单
}
const updateActivity = (Id) => {
  if (!Id || isNaN(Id)) {
    ElMessage.error('活动 ID 无效，请重新编辑');
    return;
  }

  // 构建请求体
  const requestData = {
    id: Id,

    activityName: taskForm.name,
    startDate: taskForm.time[0],
    endDate: taskForm.time[1],
    describes: taskForm.desc,
    shopIds: taskForm.store,
    targetCustomer: taskForm.crowd,
    activityTarget: taskForm.target,
    deliveryChannel: taskForm.channels.join(','),
    rewardType: taskForm.rewardType === '优惠券' ? 1 : taskForm.rewardType === '积分' ? 2 : 3,
    rewardCouponId: taskForm.reward,
    shareProfile: taskForm.summary,
    shareUrl: taskForm.link,
    enableStatus: taskForm.enableStatus,
    activityType: taskForm.activityType,
    channelType: taskForm.channelType
  };

  // 调用后端更新接口
  axios.post(`http://localhost:8087/vv1/activity/update/`+Id, requestData)
      .then(response => {
        if (response.data.code === 2000) {
          ElMessage.success('修改成功!');
          dialogVisible.value = false;
          loadUser(); // 刷新活动列表
        } else {
          ElMessage.error(response.data.msg || '修改失败，请重试');
        }
      })
      .catch(error => {
        console.error('更新活动失败:', error);
        ElMessage.error('网络错误，更新失败');
      });
};



</script>

<style scoped>
.activity-management {
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 20px;
  background: #fff;
}

.list-card {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fff;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 新建活动弹窗样式 */
.activity-type-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

.activity-type-item {
  width: 80px;
  height: 80px;
  border: 1px solid #ccc;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  margin: 10px;
  transition: all 0.3s;
}

.activity-type-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.activity-type-item.active {
  background-color: #f0f0f0;
  border-color: #409eff;
}

.activity-type-item i {
  font-size: 24px;
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: right;
}
</style>